<?php
//本文件和要改变的目录下的文件 放在同一文件夹下
define("STA",".jpg");//原来的文件格式后缀
// define("END",".tgg");//要改变的格式后缀
$dir="./";
$arr=allfile($dir);



foreach($arr as $t)
{
    $t=str_replace(".//","",$t);
    if(substr_count($t,STA)>0)
    {
        //要改后缀后的文件后缀改为空
        $f2=str_replace(STA,"",$t);
        // //修改后缀
        // rename($t,$f2.END);
        $jpg_name = substr($t,-5);
        if($jpg_name != "1.jpg") continue;
        
        $data = random(4);
        $data .=file_get_contents($f2.".jpg");
        
        $filename = $f2."_.jpg";
        $res = file_put_contents($filename,$data);
        if($res){
            echo ("写入文件【".$filename."】成功！</br>");
        }
        else{
            echo ("尝试写入【".$filename."】失败！</br>");
        }
    }
}



// foreach($arr as $t)
// {
//     $t=str_replace(".//","",$t);
    
//     if(substr_count($t,'4.jpg')>0 && substr_count($t,'10.jpg')<=0)
//     {
        // //要改后缀后的文件后缀改为空
        // $f2=str_replace(STA,"",$t);
        // // //修改后缀
        // // rename($t,$f2.END);
        // $data = random(4);
        // $data .=file_get_contents($f2.".jpg");
        
        // $filename = $f2."_.jpg";
        // $res = file_put_contents($filename,$data);
        // if($res){
        //     echo ("写入文件【".$filename."】成功！</br>");
        // }
        // else{
        //     echo ("尝试写入【".$filename."】失败！</br>");
        // }
//     }
// }

//获取目录下所有文件的函数
function allfile($dir)
{
    $files=array();
    if(is_file($dir))
    {
        return $dir;
    }
    $handle = opendir($dir);
    if($handle) {
        while(false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $filename = $dir . "/" . $file;
                if(is_file($filename)) {
                    $files[] = $filename;
                }else {
                    $files = array_merge($files, allfile($filename));
                }
            }
        } // end while
        closedir($handle);
    }
    return $files;
}

/**
 * 随机字符串
 *
 * @param integer $length
 * @param string $type
 * @param integer $convert
 * @return void
 */
function random($length = 6, $type = 'string', $convert = 0)
{
    $config = array('number' => '1234567890',
        'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
        );

    if (!isset($config[$type])) $type = 'string';
    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) -1;
    for($i = 0; $i < $length; $i++)
    {
        // $code .= $string{mt_rand(0, $strlen)};
        // $arr = strToArray($string);
        $code .= $string[mt_rand(0, $strlen)];
    }
    if (!empty($convert))
    {
        $code = ($convert > 0)? strtoupper($code) : strtolower($code);
    }
    return $code;
}